package com.ruoyi.system.service.impl;

import java.util.Date;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.CustomConfig;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.mapper.CustomConfigMapper;
import com.ruoyi.system.service.ICustomConfigService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class CustomConfigServiceImpl implements ICustomConfigService
{
    @Autowired
    private CustomConfigMapper customConfigMapper;

    @Override
    public CustomConfig load(QueryVo queryVo) {
        CustomConfig customConfig = customConfigMapper.retrieve(queryVo);
        if (customConfig == null) {
            customConfig = new CustomConfig();
            JSONObject filters = queryVo.getFilters();
            customConfig.setName(filters.getString("name"));
            customConfig.setValue("");
        }
        return customConfig;
    }

    @Override
    public Boolean save(CustomConfig customConfig) {
        Boolean done = false;
        try {
            Integer affected = 0;
            QueryVo queryVo = new QueryVo();
            queryVo.filters.put("name", customConfig.getName());
            queryVo.filters.put("company_id", customConfig.getCompanyId());
            CustomConfig target = customConfigMapper.retrieve(queryVo);
            if (target == null) {
                customConfig.setCreateTime(new Date());
                affected = customConfigMapper.create(customConfig);
            } else {
                customConfig.setId(target.getId());
                affected = customConfigMapper.update(customConfig);
            }
            if (affected > 0) {
                done = true;
            }
        } catch (Exception e) {
            log.info("",e);
            StackTraceElement[] traces = e.getStackTrace();
            for (StackTraceElement trace : traces) {
                log.debug(trace.toString());
            }
        }
        return done;
    }
}
